<template>
  <div>
    <BasicTable @register="registerTable">
      <template #headerTop>
        <Alert v-if="checkedKeys.length > 0" type="info" show-icon style="position: relative">
          <template #message>
            <div>
              <span>已选中{{ checkedKeys.length }}条记录</span>
              <div style="position: absolute; top: 4px; right: 10px">
                <Tooltip title="删除">
                  <a-button type="text" @click="handleSelectedDelete">
                    <Icon :icon="ICON.DELETE" color="#0960bd" />
                  </a-button>
                </Tooltip>
              </div>
            </div>
          </template>
        </Alert>
      </template>

      <template #toolbar>
        <Button type="primary" @click="addRecipient">
          <Icon icon="ant-design:plus-outlined" />
          添加收件人
        </Button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'ant-design:edit-filled',
                tooltip: {
                  title: '编辑',
                  placement: 'top',
                },
                onClick: editRecipient.bind(null, record),
              },
              {
                icon: 'ic:baseline-delete',
                tooltip: {
                  title: '删除',
                  placement: 'top',
                },
                onClick: deleteOneRecipient.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <!--添加通知收件人组弹窗-->
    <CreateRecipientModal @register="registerModal" @close-flag="getCloseFlag" />
    <SysCreaterecipirnt @register="sysRegisterModal" @sys-close-flag="getCloseFlag" />
  </div>
</template>

<script lang="ts" setup>
  import Icon from '/@/components/Icon/src/Icon.vue';
  import SysCreaterecipirnt from './SysCreaterecipirnt.vue';
  import CreateRecipientModal from './CreateRecipientModal.vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { recipientColumns, searchFormSchema, recipientType } from '../data/notification.data';
  import { tableFormStyleSetting, tableStyleSetting } from '/@/settings/thingsBoardDesign';
  import { onMounted, ref } from 'vue';
  import { getTargetsList, deleteTheTargets } from '/@/api/thingsborad/notification/notification';
  import { notificationsParams } from '/@/api/thingsborad/notification/model/notificationsModel';
  import { Button, Tooltip, Alert } from 'ant-design-vue';
  import dayjs from 'dayjs';
  import { ICON } from '/@/enums/iconEnum';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import { usePermission } from '/@/hooks/web/usePermission';
  const { hasPermission } = usePermission();
  // 消息通知框
  const { createConfirm } = useMessage();
  //多选数组
  let checkedKeys = ref<any>([]);
  //请求参数
  let params = ref<notificationsParams>({
    pageSize: 10,
    page: 0,
    sortProperty: 'createdTime',
    sortOrder: 'DESC',
  });
  // 表格数据
  let tableList = ref<any>([]);
  onMounted(() => {
    setProps({
      api: getTargetsList,
      beforeFetch: (val) => {
        params.value.page = val.page - 1;
        params.value.pageSize = val.pageSize;
        params.value.sortOrder = val.order == 'ascend' ? 'ASC' : 'DESC';
        params.value.sortProperty = 'createdTime';
        params.value.unreadOnly = true;
        if (val.name === null) {
          params.value.textSearch = undefined;
        } else {
          params.value.textSearch = val.name;
        }
        return params.value;
      },
      afterFetch: (res) => {
        tableList.value = [];
        if (res.length === 0) {
          return tableList.value;
        }
        res.forEach((item) => {
          tableList.value.push({
            createdTime: dayjs(item.createdTime).format('YYYY-MM-DD HH:mm:ss'),
            name: item.name,
            type: recipientType[item.configuration.type],
            description: item.configuration.description,
            id: item.id.id,
            info: item,
          });
        });
        return tableList.value;
      },
      fetchSetting: {
        pageField: 'page',
        sizeField: 'pageSize',
        listField: 'data',
        totalField: 'totalElements',
      },
    });
    setModalProps({
      width: 800,
      height: 350,
    });
    sysSetModalProps({
      width: 800,
      height: 350,
    });
  });
  // 添加通知收件人组
  const [registerModal, { openModal, setModalProps }] = useModal();
  // 添加通知收件人组
  const [sysRegisterModal, { openModal: sysOpenModal, setModalProps: sysSetModalProps }] =
    useModal();
  // 添加收件人
  const addRecipient = () => {
    if (hasPermission('SYS_ADMIN')) {
      sysOpenModal(true, true);
    } else {
      openModal(true, true);
    }
  };
  //表格初始化
  const [registerTable, { reload, setProps }] = useTable({
    columns: recipientColumns,
    ...tableStyleSetting,
    formConfig: {
      layout: 'horizontal',
      schemas: searchFormSchema,
      showAdvancedButton: false,
      submitFunc: async () => {
        reload();
      },
      ...tableFormStyleSetting,
      actionColOptions: {
        md: { span: 8, offset: 16 },
        lg: { span: 6, offset: 16 },
        xl: { span: 4, offset: 16 },
        xxl: { span: 4, offset: 16 },
      },
    },
    rowKey: 'id',
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys: checkedKeys,
      onSelect: onSelect,
      onSelectAll: onSelectAll,
    },
  });
  // 多选删除
  const handleSelectedDelete = () => {
    createConfirm({
      iconType: 'info',
      title: `确定要删除      '${checkedKeys.value.length}'     个收件人吗？`,
      content: '请注意：确认后，收件人及其所有相关数据将不可恢复。',
      onOk: async () => {
        for (const item of checkedKeys.value) {
          await deleteTheTargets(`/${item}`);
        }
        reload();
        checkedKeys.value = [];
      },
    });
  };

  // 多选
  function onSelect(record, selected) {
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, record.id];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => id !== record.id);
    }
  }
  // 全选
  function onSelectAll(selected, _selectedRows, changeRows) {
    const changeIds = changeRows.map((item) => item.id);
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, ...changeIds];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id) => {
        return !changeIds.includes(id);
      });
    }
  }
  // 删除收件箱单条信息
  async function deleteOneRecipient(record: Recordable) {
    let paramsURL = '/' + record.id;
    createConfirm({
      iconType: 'info',
      title: `确定要删除收件人      '${record.id}'      吗？`,
      content: '请注意，在确认后，收件人将无法恢复。',
      onOk: async () => {
        await deleteTheTargets(paramsURL);
        reload();
      },
    });
  }
  function editRecipient(record: Recordable) {
    if (hasPermission('SYS_ADMIN')) {
      sysOpenModal(true, record);
    } else {
      openModal(true, record);
    }
  }

  function getCloseFlag() {
    reload();
  }
</script>
